<template>
	<view class="login">
		<!-- #ifdef MP-WEIXIN -->
		<view v-if="userLoginType==1" class="mpwx-login flex-col col-center" style="margin-top: 200rpx;">
			<view class="avatar">
				<open-data type="userAvatarUrl"></open-data>
			</view>
			<view class="user-name mt20">
				<open-data type="userNickName"></open-data>
			</view>
			<button v-if="appConfig.register_user_info == 'mobile'" size="lg" class="white br60 flex row-center btn" open-type="getPhoneNumber" type="primary" shape="circle" @getphonenumber="getPhoneNumber">
				<text>手机快捷登录</text>
			</button>
			<button v-else size="lg" class="white br60 flex row-center btn" @click="mnpLoginFun">
				<text>手机快捷登录</text>
			</button>
			<!-- <button size="lg" class="white br60 flex row-center btn" open-type="getUserInfo" type="primary" shape="circle" @getuserinfo="onGetUserInfo">
				<text>手机快捷登录</text>
			</button> -->
			
			<view class="md muted m-t-10" @tap="noLongin">暂不登录 ></view>
			<view class="muted m-t-10">本商城进允许通过专属链接邀请注册哦</view>
			<view class="m-t-30  sm flex row-center">
				<u-checkbox v-model="isAgreement" shape="circle">
					<div class="flex">
						已阅读并同意
						<router-link to="/bundle/pages/server_explan/server_explan?type=0">
							<view class="primary">《服务协议》</view>
						</router-link>
						和
						<router-link to="/bundle/pages/server_explan/server_explan?type=1">
							<view class="primary">《隐私协议》</view>
						</router-link>
					</div>
				</u-checkbox>
			</view>
		</view>
		<mplogin-popup v-model="showLoginPop" :logo="appConfig.shop_login_logo" :title="appConfig.name"
			:login-data="loginData" @close="closePopup" @update="handleSubmitInfo" />
		<view v-if="userLoginType==2">
			<view class="acount-login">
				<image class="logo" :src="appConfig.shop_login_logo" mode="heightFix"></image>
				<view v-if="loginType == 0">
					<view class="input">
						<u-input v-model="mobile" style="width: 100%" placeholder="请输入账户/手机号" :input-border="false" />
					</view>
					<view class="input flex" style="padding: 15rpx 0">
						<u-input v-model="password" type="password" style="flex: 1" :password-icon="false"
							placeholder="请输入密码" :input-border="false" />
						<navigator style="width: 132rpx; border-left: 1rpx solid #ccc"
							url="/bundle/pages/forget_pwd/forget_pwd" hover-class="none">忘记密码</navigator>
					</view>
				</view>
				<view v-if="loginType == 1">
					<view class="input">
						<u-input v-model="telephone" style="width: 100%" placeholder="手机号" :input-border="false" />
					</view>
					<view class="input flex" style="padding: 15rpx 0">
						<u-input v-model="smsCode" style="flex: 1" placeholder="请输入验证码" :input-border="false" />
						<view class="flex">
							<view class="sms-btn primary flex row-center br60" @click="$sendSms">
								<!-- 获取验证码 -->
								<u-verification-code unique-key="login" ref="uCode" @change="codeChange">
								</u-verification-code>
								<view class="xs">{{ codeTips }}</view>
							</view>
						</view>
					</view>
				</view>
				<button style="margin: 80rpx 0 50rpx; width: 680rpx" size="lg" class="br60" type="primary"
					@click="loginFun">
					登录
				</button>
				<view class="flex row-between" style="width: 680rpx">
					<view class="lighter" @click="changeLoginType">{{
			            loginType == 0 ? "短信验证码登录" : "账号登录"
			        }}</view>
					<navigator class="lighter" url="/bundle/pages/register/register" hover-class="none">注册账号</navigator>
				</view>
			</view>
		</view>
		<!--  #endif -->

	</view>
</template>

<script>
	import {
		mapMutations,
		mapActions,
		mapGetters
	} from "vuex";
	import {
		accountLogin,
		codeLogin,
		sendSms,
		wxpLogin,
		smsCodeLogin,
		opLogin,
		authLogin,
		authRegisterLogin,
		updateUser,
		getConfig
	} from "@/api/app";
	import {
		bindSuperior
	} from "@/api/user";
	import wechath5 from "@/utils/wechath5";
	import {
		isWeixinClient,
		currentPage,
		client,
		trottle
	} from "@/utils/tools";
	import {
		SMSType
	} from "@/utils/type";
	import Cache from "@/utils/cache";
	import {
		BACK_URL,
		INVITE_CODE,
		DISTRIBUTION,
		DISTRIBUTIONID,
		INVITE_REGISTER,
		WECHATSCENECODE
	} from "@/config/cachekey";
	import {
		getWxCode,
		getUserProfile
	} from "@/utils/login";
	const loginType = {
		ACCOUNT_LOGIN: 0,
		SMS_CODE_LOGIN: 1,
	};
	export default {
		data() {
			return {
				isAgreement: false,
				password: "",
				mobile: "",
				code: "",
				isWeixin: "",
				loginType: 0,
				smsCode: "",
				codeTips: "",
				telephone: "",
				text: "",
				showLoginPop: false,
				loginData: {},
				userLoginType: 0,
				imgUrl:`${this.$imgUrl}/wechat`
			};
		},

		async onLoad(option) {
			this.mnpLoginFun = trottle(this.mnpLoginFun);
			this.appWxLogin = trottle(this.appWxLogin);
			this.getCodeUrl = trottle(this.getCodeUrl);
			this.getuserLoginType();
			// H5微信登录
			// #ifdef H5
			this.oaAutoLogin();
			// #endif
		},
		onUnload() {},
		methods: {
			...mapMutations(["login",'setConfig','setNavigationMenu','setConfigCode']),
			...mapActions(["getUser"]),
			async onGetUserInfo(e) {
				console.log(e);
			},
			// 获取手机号回调
			async getPhoneNumber(e) {
				if (e.detail.errMsg === "privacy permission is not authorized") {
					this.$u.toast('授权失败，失败原因：未同意隐私协议')
					return;
				}
				if (e.detail.errMsg === "privacy permission is not authorized in gap") {
					this.$u.toast('授权失败，原因：未同意隐私协议，请稍后重试')
					return;
				}
				if (e.detail.errMsg === "getPhoneNumber:fail user deny") {
					this.$u.toast('授权失败，原因：用户拒绝')
					return;
				}
				if (e.detail.errMsg !== "getPhoneNumber:ok") {
					this.$u.toast(`授权失败，原因：' ${e.detail.errMsg}`)
					return;
				}
				if (!this.isAgreement)
					return this.$toast({
						title: '请先勾选"已阅读并同意《服务协议》和《隐私协议》"',
					});
				
				uni.showLoading({
					title: "登录中...",
					mask: true,
				});
				
				const logincode = await getWxCode();
				console.log('-------e.detail--------');
				console.log(e.detail);
				const {
					code,
					data,
					msg
				//} = await authLogin({
				} = await authRegisterLogin({
					code: e.detail.code,
					loginCode: logincode,
					invite_register:Cache.get(INVITE_REGISTER),
					wechat_scene_code: Cache.get(WECHATSCENECODE),
				});
				if (code == 1) {
					console.log("login------data----------", data)
					uni.hideLoading();
					this.loginHandle(data);
					this.getConfigFun()
					this.setNavigationMenu(data.navigation_menu)
				} else {
					this.$toast({
						title: msg,
					});
				}
			},
			getuserLoginType() {
				this.userLoginType = this.appConfig.invite.user_login_type
			},
			codeChange(tip) {
				this.codeTips = tip;
			},
			getCodeUrl() {
				wechath5.getWxUrl();
			},
			// 公众号微信登录
			async oaLogin(code) {
				const data = await wechath5.authLogin(code);
				this.loginHandle(data);
			},
			oaAutoLogin() {
				// H5微信登录
				const {
					code
				} = this.$Route.query;
				this.isWeixin = isWeixinClient();
				if (this.isLogin) {
					// 已经登录 => 首页
					uni.switchTab({
						url: "/pages/index/index",
					});
					return;
				}
				if (code) {
					// 带有code => 登录
					return this.oaLogin(code);
				}
				if (this.isWeixin && this.isOaWxAutoLogin) {
					// 开启自动授权登录
					this.getCodeUrl();
				}
			},
			// 小程序登录
			async mnpLoginFun() {
				if (!this.isAgreement)
					return this.$toast({
						title: '请先勾选"已阅读并同意《服务协议》和《隐私协议》"',
					});
				const {
					userInfo: {
						avatarUrl,
						nickName,
						gender
					},
				} = await getUserProfile();
				uni.showLoading({
					title: "登录中...",
					mask: true,
				});
				const wxCode = await getWxCode();
				const {
					code,
					data,
					msg
				} = await authLogin({
					code: wxCode,
					nickname: nickName,
					headimgurl: avatarUrl,
					invite_register:Cache.get(INVITE_REGISTER),
					wechat_scene_code: Cache.get(WECHATSCENECODE),
				});
				if (code == 1) {
					this.setConfigCode(code)
					if (data.is_new_user) {
						uni.hideLoading();
						this.showLoginPop = true;
						this.loginData = data;
						this.getConfigFun()
					} else {
						this.loginHandle(data);
						this.getConfigFun()
					}
					this.setNavigationMenu(data.navigation_menu)
				} else {
					this.$toast({
						title: msg,
					});
				}
			},
			noLongin(){
				this.$Router.pushTab("/pages/index/index");
			},
			async getConfigFun() {
				const {
					code,
					data
				} = await getConfig()
				if (code == 1) {
					this.setConfig(data)
				}
			},
			// 账号登录
			async loginFun() {
				/* console.log(111111111111) */
				if (!this.isAgreement)
					return this.$toast({
						title: '请先勾选"已阅读并同意《服务协议》和《隐私协议》"',
					});
				const {
					mobile,
					password,
					telephone,
					smsCode
				} = this;
				if (this.loginType == 0) {
					if (!mobile) {
						this.$toast({
							title: "请输入账户/手机号",
						});
						return;
					}
					if (!password) {
						this.$toast({
							title: "请输入密码",
						});
						return;
					}
					const {
						code,
						data
					} = await accountLogin({
						mobile,
						password,
						client: 1,
					});
					if (code == 1) {
						console.log("login", data)
						this.loginHandle(data);
					}
				} else {
					if (!telephone) {
						this.$toast({
							title: "请输入手机号",
						});
						return;
					}
					if (!smsCode) {
						this.$toast({
							title: "请输入验证码",
						});
						return;
					}
					smsCodeLogin({
						mobile: telephone,
						code: smsCode,
					}).then((res) => {
						if (res.code == 1) {
							this.loginHandle(res.data);
						}
					});
				}
			},
			// 登录结果处理
			async loginHandle(data) {
				this.login(data);
				uni.hideLoading();
				// 绑定邀请码
				const inviteCode = Cache.get(INVITE_CODE);
				if (inviteCode) {
					// bindSuperior({
					// 	code: inviteCode,
					// });
					Cache.remove(INVITE_CODE);
				}
				console.log(data);
				Cache.set(DISTRIBUTION, data.distribution);
				Cache.set(DISTRIBUTIONID, data.distribution.id);
				Cache.set(INVITE_CODE, data.distribution.invite_code);
				if (getCurrentPages().length > 1) {
					uni.navigateBack({
						success() {
							const {
								onLoad,
								options
							} = currentPage();
							onLoad && onLoad(options);
						},
					});
				} else if (Cache.get(BACK_URL)) {
					this.$Router.replace(Cache.get(BACK_URL));
				} else {
					this.$Router.pushTab("/pages/index/index");
				}
				Cache.remove(BACK_URL);
			},
			changeLoginType() {
				if (this.loginType == loginType.ACCOUNT_LOGIN) {
					this.loginType = loginType.SMS_CODE_LOGIN;
				} else if (this.loginType == loginType.SMS_CODE_LOGIN) {
					this.loginType = loginType.ACCOUNT_LOGIN;
				}
			},
			// 发送验证码
			$sendSms() {
				if (!this.$refs.uCode.canGetCode) return;
				if (!this.telephone) {
					this.$toast({
						title: "请输入手机号",
					});
					return;
				}

				sendSms({
					mobile: this.telephone,
					key: SMSType.LOGIN,
				}).then((res) => {
					if (res.code == 1) {
						this.$refs.uCode.start();
						this.$toast({
							title: res.msg,
						});
					}
				});
			},
			// app微信登录
			async appWxLogin() {
				if (!this.isAgreement)
					return this.$toast({
						title: '请先勾选"已阅读并同意《服务协议》和《隐私协议》"',
					});
				uni.login({
					provider: "weixin",
					success: (res) => {
						uni.showLoading({
							title: "登录中...",
							mask: true,
						});
						const {
							openid,
							access_token
						} = res.authResult;
						opLogin({
								openid,
								access_token,
							})
							.then((res) => {
								uni.hideLoading();
								if (res.code == 1) {
									this.loginHandle(res.data);
								}
							})
							.catch(() => {
								uni.hideLoading();
							});
					},
				});
			},
			async handleSubmitInfo(e) {
				const loginData = this.loginData
				const res = await updateUser(e, loginData.token);
				if (res.code == 1) {
					this.loginHandle(loginData);
				}
			},
			closePopup() {
				this.showLoginPop = false;
			},
		},
		computed: {
			...mapGetters(["appConfig"]),
			isOaWxAutoLogin() {
				return this.appConfig.wechat_h5;
			},
		},
	};
</script>
<style lang="scss">
	page {
		background-color: #fff;
		text-align: center;
		padding: 0;

		.login {
			min-height: 100vh;
			display: flex;
			flex-direction: column;

			.mpwx-login {
				min-height: 0;
				flex: 1;

				.avatar {
					display: inline-block;
					width: 120rpx;
					height: 120rpx;
					border-radius: 50%;
					border: 1px solid #eee;
					overflow: hidden;
				}

				.user-name {
					height: 40rpx;
				}

				.image {
					width: 50rpx;
					height: 50rpx;
				}

				.btn {
					background-color: #00642B;
					width: 580rpx;
					margin: 80rpx auto 0;
				}
			}

			.acount-login {
				padding-top: 100rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				box-sizing: border-box;
				min-height: 0;
				flex: 1;

				.logo {
					height: 80rpx;
					margin-bottom: 50rpx;
				}

				.input {
					width: 670rpx;
					border-bottom: $-solid-border;
					margin-top: 30rpx;
				}

				.sms-btn {
					border: 1px solid $-color-primary;
					width: 176rpx;
					height: 60rpx;
					box-sizing: border-box;
				}

				.wx-login {
					margin-top: 60rpx;

					.image {
						margin-top: 40rpx;
						width: 80rpx;
						height: 80rpx;
					}
				}
			}
		}
	}
</style>